package com.xtoad.ecms.baseinfo.controller;

import com.xtoad.ecms.baseinfo.dto.LoginDTO;
import com.xtoad.ecms.baseinfo.dto.RegisterDTO;
import com.xtoad.ecms.baseinfo.dto.UserDTO;
import com.xtoad.ecms.baseinfo.service.IUserService;
import com.xtoad.ecms.common.utils.PasswordUtils;
import com.xtoad.ecms.common.utils.TokenUtils;
import com.xtoad.ecms.common.web.UserContext;
import com.xtoad.ecms.common.web.annotation.PrintRequestInfo;
import com.xtoad.ecms.common.web.annotation.RequiredToken;
import com.xtoad.ecms.common.web.annotation.ResponseAdvice;
import com.xtoad.ecms.common.web.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录 控制器
 *
 * @author xtoad
 * @date 2020/05/29
 */
@RestController
@RequestMapping("auth")
@ResponseAdvice
public class AuthController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Resource
    private IUserService userService;

    /**
     * 注册接口
     *
     * @return 注册用户信息
     */
    @PrintRequestInfo
    @RequiredToken(value = false)
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public UserDTO register(@Valid @RequestBody final RegisterDTO userDTO, HttpServletResponse response) {
        UserDTO user = userService.getUserByLoginNo(userDTO.getLoginNo());
        if (user != null) {
            throw new BusinessException("000003", "用户已经被注册");
        }
        Date dateNow = new Date();
        UserDTO dto = new UserDTO();
        dto.setId(null);
        dto.setName(userDTO.getName());
        dto.setLoginNo(userDTO.getLoginNo());
        dto.setPassword(PasswordUtils.encode(userDTO.getPassword()));
        dto.setNickName(userDTO.getNickName());
        dto.setEmail(userDTO.getEmail());
        dto.setPhone(userDTO.getPhone());
        dto.setBirthday(userDTO.getBirthday());
        dto.setSex(userDTO.getSex());
        dto.setCreateTime(dateNow);
        dto.setCreateUser(userDTO.getName());
        dto.setLastUpdateTime(dateNow);
        dto.setLastUpdateUser(userDTO.getName());
        user = userService.insert(dto);
        setHeader(user, response);

        return user;
    }

    /**
     * 登录接口
     *
     * @return 登录用户信息
     */
    @PrintRequestInfo
    @RequiredToken(value = false)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public UserDTO login(@Valid @RequestBody final LoginDTO loginDTO, HttpServletResponse response) {
        UserDTO user = userService.getUserByLoginNo(loginDTO.getLoginNo());
        if (user == null || !PasswordUtils.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("000003", "输入的用户名或密码不正确");
        }
        setHeader(user, response);
        user.setPassword(null);

        return user;
    }

    /**
     * 登出接口
     *
     * @return Hello World
     */
    @PrintRequestInfo
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Boolean logout() {

        return true;
    }

    /**
     * 根据Token获取用户信息
     *
     * @return Hello World
     */
    @PrintRequestInfo
    @RequestMapping(value = "/getCurrentUser", method = RequestMethod.GET)
    public UserDTO getUserByToken() {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(UserContext.getUserId());
        userDTO.setLoginNo(UserContext.getLoginNo());
        userDTO.setName(UserContext.getUserName());
        userDTO.setNickName(UserContext.getNickName());

        return userDTO;
    }

    /**
     * 设置请求的响应头内容
     *
     * @param user     当前登录用户信息
     * @param response 相应对象
     */
    private void setHeader(UserDTO user, HttpServletResponse response) {
        LOGGER.info("[login] username is {}，userId is {}", user.getLoginNo(), user.getId());
        Map<String, String> tokenInfo = new HashMap<>(6);
        tokenInfo.put(UserContext.CONTEXT_KEY_USER_ID, user.getId().toString());
        tokenInfo.put(UserContext.CONTEXT_KEY_LOGIN_NO, user.getLoginNo());
        tokenInfo.put(UserContext.CONTEXT_KEY_USER_NICK_NAME, user.getNickName());
        tokenInfo.put(UserContext.CONTEXT_KEY_USER_NAME, user.getName());
        String token = TokenUtils.generateToken(tokenInfo);
        // 跨域访问允许访问的响应头的内容
        response.setHeader("Access-Control-Expose-Headers", TokenUtils.TOKEN_HEADER);
        response.addHeader(TokenUtils.TOKEN_HEADER, token);
    }
}
